//
//  StatusCellPictureView.swift
//  SinaWeibo
//
//  Created by apple on 15/11/16.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit
import SDWebImage

let PictureMargin :CGFloat = 5

private let PictureCellID = "PictureCellID"

class StatusCellPictureView: UICollectionView {
 
    //配图视图
    var imageURLs :[NSURL]? {
        
        didSet{
            
           // print(imageURLs) 测试
            
            //刷新数据
            reloadData()
            
            let viewSize = self.calculatePicSize()
            
            self.snp_updateConstraints { (make) -> Void in
                
                make.width.equalTo(viewSize.width)
                
                make.height.equalTo(viewSize.height)
            }
        
        }
    }
    
    //计算 单张 4张 多张配图的尺寸
    private func calculatePicSize () ->CGSize {
        
        let column :CGFloat = 3.0000000000001
        
        let maxWidth = screenWidth - 2 * StatusCellMargin
        
        let itemSize = (maxWidth - 2 * PictureMargin) / column
        
        let layout = self.collectionViewLayout as? UICollectionViewFlowLayout
        
        layout?.itemSize = CGSizeMake(itemSize, itemSize)
        
       
        //图片的个数
        let imageCount = imageURLs?.count ?? 0
        
        if imageCount == 0 {
            
            return CGSizeZero
        }
        //单张图片
        if imageCount == 1 {
            
            //获取单张被缓存的图片
            let key = imageURLs?.last?.absoluteString
            let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(key!)
            
            
            let imageSize = image.size

            
            layout?.itemSize = imageSize
            
            return imageSize
            
            
        }
        
        //4 张图片
        if imageCount == 4 {
            
            let w = itemSize * 2 + PictureMargin
            
            return CGSizeMake(w, w)
        }
        
        //多张图片 九宫格布局
       
        //1 , 2 , 3 - > 1
        //计算行索引
        let rowIndex = CGFloat((imageCount - 1) / 3 + 1)
        
        let w = maxWidth
        
        let h = rowIndex * itemSize + (rowIndex - 1) * PictureMargin
        
        return CGSizeMake(w, h)
        
    }
    
    //MARK 初始化
    init() {
        
        //设置流水布局
        let layout = UICollectionViewFlowLayout()
        //设置Layout的参数
        layout.minimumInteritemSpacing = PictureMargin
        layout.minimumLineSpacing = PictureMargin
        
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        //注册单元格
        registerClass(pictureCell.self, forCellWithReuseIdentifier: PictureCellID)
        
        //设置数据源
        dataSource = self
        
        setUPUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK 设置 UI
    private func setUPUI () {
        
        
        backgroundColor = UIColor.clearColor()
        
    }
    //MARK 懒加载控件
    
    
}

//MARK 数据源 方法
extension StatusCellPictureView :UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return imageURLs?.count ?? 0
    
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
       
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureCellID, forIndexPath: indexPath) as? pictureCell
        
//        cell.backgroundColor = UIColor.randomColor()
        
        cell?.url = imageURLs![indexPath.row]
        return cell!
    }
}

class pictureCell:UICollectionViewCell {
    
    var url :NSURL? {
    
      didSet {
      
        imageView.sd_setImageWithURL(url, placeholderImage: nil)
    
      }
    }
    
    //MARK 初始化方法
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setUPUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK 设置 UI 
    private func setUPUI () {
        
        //添加子控件
        contentView.addSubview(imageView)
        
        //设置约束
        imageView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(contentView.snp_edges)
        }
    }
    
    //MARK 懒加载控件
    private lazy var imageView :UIImageView = {
        
        let imageView = UIImageView()
        
        //设置显示样式
        imageView.contentMode = UIViewContentMode.ScaleAspectFill
        //设置裁剪
        imageView.clipsToBounds = true
        
        return imageView
        
    }()
}